package com.jcc.cm.ali.controller;

import com.aliyuncs.ecs.model.v20140526.*;
import com.jcc.springcloud.cloud.DescribeCloud;
import com.jcc.springcloud.result.CommonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.rmi.ServerException;

@RequestMapping("/")
@RestController
public class AliApiServiceController {
    //查询主机当前状态（初始化中、'Stopped'、'Running'）


    @Value("${ali.AccessKeyId}")
    private String AccessKeyId;


    @Value("${ali.AccessKeySecret}")
    private String AccessKeySecret;

    @Value("${ali.InternetChargeType}")
    private String InternetChargeType;

    @Value("${ali.InternetMaxBandwidthOut}")
    private int InternetMaxBandwidthOut;


    @PostMapping(value = "/CreateInstanceGetIp")
    @ResponseBody
    public CommonResult create_instance_get_ip(@RequestBody DescribeCloud db){



        DefaultProfile profile = DefaultProfile.getProfile(db.getRegionId(),AccessKeyId,AccessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

//        DescribeInstancesRequest request = new DescribeInstancesRequest();


        //创建请求
        RunInstancesRequest request = new RunInstancesRequest ();

        //请求的基本参数
        request.setRegionId(db.getRegionId());
        request.setImageId(db.getImageId());
        request.setInstanceType(db.getInstanceType());
        request.setInternetMaxBandwidthOut(InternetMaxBandwidthOut);
        request.setInternetChargeType(InternetChargeType);


        //数据盘暂时不装


        //发送请求
        RunInstancesResponse response;
        try {
            response = client.getAcsResponse(request);

            //打印日志
//            System.out.println(JSON.toJSONString(response));

        } catch (ServerException e) {

            //打印错误日志
//            e.printStackTrace();
            return new CommonResult(-1,String.format("{\"Error\":%s}","请求失败，创建实例失败".concat(e.getErrMsg())));
        } catch (ClientException e) {


            //打印错误日志
//            System.out.println("ErrCode:" + e.getErrCode());
//            System.out.println("ErrMsg:" + e.getErrMsg());
//            System.out.println("RequestId:" + e.getRequestId());
            return new CommonResult(-2,String.format("{\"Error\":%s}","客户端异常，创建实例失败:".concat(e.getErrMsg())));
        }

        String instanceId = response.getRequestId();

        //阿里云需要主机初始化完成之后才能分配公网ip，即需要主机状态为Stopped，再分配ip，否则报错

        DescribeInstancesResponse.Instance instance;
        int i = 0;
        do{
            instance = getInstanceInfo(client,instanceId,db.getRegionId());

            if(instance != null) break;
            i++;
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
            }
        }while (i<50);

        if(instance == null){
            return new CommonResult(-3,String.format("{\"Error\":%s}","获取实例信息失败"));
        }
        //开始分配IP

        AllocatePublicIpAddressRequest arequest = new AllocatePublicIpAddressRequest();
        arequest.setInstanceId(instanceId);

        String publicIp = "";
        try {
            AllocatePublicIpAddressResponse aresponse = client.getAcsResponse(arequest);
            if(aresponse != null){
                publicIp.concat(aresponse.getIpAddress());
            }
        } catch (ClientException e) {
//            e.printStackTrace();
            return new CommonResult(-2,String.format("{\"Error\":%s}","客户端异常,IP分配失败:".concat(e.getErrMsg())));
        }

        //启动主机
        StartInstanceRequest srequest = new StartInstanceRequest();
        srequest.setInstanceId(instanceId);

        try {
            StartInstanceResponse sresponse = client.getAcsResponse(srequest);
            if(srequest != null){
                //返回公网IP
                return new CommonResult(1,String.format("{\"InstanceId\":%s,\"PublicIp\":%s}",instanceId,publicIp));
            }
        } catch (ClientException e) {
            return new CommonResult(-2,String.format("{\"Error\":%s}","客户端异常:".concat(e.getErrMsg())));
        }


        return new CommonResult(-4,String.format("{\"Error\":%s}","实例启动失败"));
    }



    private DescribeInstancesResponse.Instance getInstanceInfo(IAcsClient client, String instanceId, String regionid){

        // 创建API请求并设置参数。
        DescribeInstancesRequest request = new DescribeInstancesRequest();
        request.setRegionId(regionid);
        request.setInstanceIds(instanceId);
        try {
            DescribeInstancesResponse response = client.getAcsResponse(request);
            for (DescribeInstancesResponse.Instance instance : response.getInstances())
            {
//                System.out.println(instance.getImageId());
//                System.out.println(instance.getInstanceId());
//                System.out.println(instance.getPublicIpAddress());
                if(instance.getStatus() != null && instance.getStatus().equals("stopped")){
                    return instance;
                }
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;

    }



    @RequestMapping("/GetPrices")
//    @PostMapping("/GetPrices")
    public CommonResult getPrice(/*@RequestBody DescribeCloud db*/){

        DescribeCloud db = new DescribeCloud();

        db.setInstanceType("ecs.g5.xlarge");
        db.setRegionId("cn-hangzhou");


        DefaultProfile profile = DefaultProfile.getProfile(db.getRegionId(),AccessKeyId,AccessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);


        DescribePriceRequest request = new DescribePriceRequest();
        request.setInstanceType(db.getInstanceType());
//        request.setRegionId("cn-hangzhou");


        try{
            DescribePriceResponse response = client.getAcsResponse(request);
            return new CommonResult(1, new Gson().toJson(response));
//            return new CommonResult(1,String.format("{%s:%s}",db.getInstanceType(),response.getPriceInfo().getPrice().getTradePrice()));
        }
        catch (ClientException e){

            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
            return new CommonResult(-1,String.format("{ClientException:%s}",e.fillInStackTrace()));
        }
    }


    @PostMapping("/DestroyInstance")
    public CommonResult destroy_instance(@RequestBody DescribeCloud db){
        DefaultProfile profile = DefaultProfile.getProfile(db.getRegionId(),AccessKeyId,AccessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);


        DeleteInstanceRequest request = new DeleteInstanceRequest();
        request.setInstanceId(db.getInstanceId());
        request.setForce(true);

        try {
            DeleteInstanceResponse response = client.getAcsResponse(request);
            return new CommonResult(1,"删除成功");
        } catch (ClientException e) {
            return new CommonResult(-1,String.format("{删除失败:%s}",e.getErrMsg()));

        }
    }

}
